<template>
  <!-- 首页 -->
  <a-layout>
    <a-layout-header class="header flex justify-between w-full bg-white">
      <div class="flex items-center cursor-pointer" @click="handleLogoClick">
        <img src="/images/logo.jpg" class="logo" height="28" alt="" />
        <h1 class="title font-bold mb-0 ml-2 leading-none">百搜优化</h1>
      </div>
      <div class="layout__right">
        <!-- <a-button type="link" class="btn" @click="openOperationalTool" v-if="mainStore.isOperation">
          运营工具
        </a-button> -->
        <a-dropdown>
          <div>
            <a-avatar class="layout__right__avatar" shape="circle" size="small">
              <template #icon>
                <img src="/images/avatar.png" alt="" />
              </template>
            </a-avatar>
            <a class="layout__right__username" @click.prevent>
              {{ mainStore.userInfo?.full_name }}
            </a>
          </div>
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="handleLogout">退出登录</a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </div>
    </a-layout-header>
    <a-layout>
      <div class="fake-sider" :class="{ 'fake-sider--collapsed': collapsed }"></div>
      <a-layout-sider
        class="real-sider"
        width="208"
        theme="light"
        v-model:collapsed="collapsed"
        :trigger="null"
        breakpoint="xl"
        collapsible
        collapsedWidth="48px"
        @breakpoint="handleBreakpoint"
      >
        <scrollbar class="menu__scroll-bar">
          <a-menu
            v-model:selectedKeys="baseState.selectedKeys"
            v-model:openKeys="baseState.openKeys"
            mode="inline"
            :multiple="true"
            :inline-collapsed="collapsed"
            @click="handleMenuClick"
          >
            <template v-for="item in list" :key="item.path">
              <template v-if="!item.children?.length">
                <a-menu-item :key="item.path">
                  <template #icon>
                    <icon-park v-if="item.meta?.icon" :type="item.meta?.icon" theme="filled" :size="16" />
                  </template>
                  {{ item.meta?.title }}
                </a-menu-item>
              </template>
              <template v-else>
                <a-sub-menu :key="item.path">
                  <template #icon>
                    <icon-park v-if="item.meta?.icon" :type="item.meta?.icon" theme="filled" :size="16" />
                  </template>
                  <template #title>
                    <span>{{ item.meta?.title }}</span>
                  </template>
                  <a-menu-item v-for="i in item.children" :key="i.path">
                    <span :class="{ gy: i.path === '/price-package-hjbw' }"> {{ i.meta?.title }} </span>
                  </a-menu-item>
                </a-sub-menu>
              </template>
            </template>
          </a-menu>
        </scrollbar>
        <div class="real-sider__fold cursor-pointer bg-white" @click="handleCollapse">
          <menu-unfold-outlined class="fold" v-if="collapsed" />
          <menu-fold-outlined class="unfold" v-else />
        </div>
      </a-layout-sider>
      <!-- <scrollbar class="w-full" :style="{ height: '100vh' }">
        <a-layout class="relative">
          <header class="fake-header"></header>
          <a-breadcrumb class="breadcrumb">
            <a-breadcrumb-item class="breadcrumb__item">
              <appstore-outlined />
            </a-breadcrumb-item>
            <a-breadcrumb-item :key="item.path" v-for="item in breadcrumb" class="breadcrumb__item">{{
              item.breadcrumbName
            }}</a-breadcrumb-item>
          </a-breadcrumb>
          <a-layout-content class="layout-content">
            <router-view v-slot="{ Component }">
              <keep-alive :include="keepName">
                <component :is="Component" />
              </keep-alive>
            </router-view>
          </a-layout-content>
          <div id="footer-space"></div>
        </a-layout>
      </scrollbar>-->
      <a-layout class="relative main-layout">
        <header class="fake-header"></header>
        <a-breadcrumb class="breadcrumb">
          <a-breadcrumb-item class="breadcrumb__item">
            <appstore-outlined />
          </a-breadcrumb-item>
          <a-breadcrumb-item :key="item.path" v-for="item in breadcrumb" class="breadcrumb__item">
            {{ item.breadcrumbName }}
          </a-breadcrumb-item>
        </a-breadcrumb>
        <a-layout-content class="layout-content">
          <router-view v-slot="{ Component }">
            <keep-alive :include="keepName">
              <component :is="Component" />
            </keep-alive>
          </router-view>
        </a-layout-content>
        <div id="footer-space"></div>
      </a-layout>
    </a-layout>
  </a-layout>
  <a-modal
    v-model:visible="GuideVisible"
    :closable="false"
    width="900px"
    :title="null"
    @cancel="handleCancel(1, priceAsk?.priceAskIdList)"
  >
    <template #footer>
      <a-button type="primary" @click="handleCancel(1, priceAsk?.priceAskIdList)">关闭</a-button>
    </template>
    <p style="font-size: 18px; font-weight: 600; color: red; margin-bottom: 40px">
      {{ priceAsk?.title }}
    </p>
    <p style="color: #999">
      {{ priceAsk?.content }}
      <a :href="priceAsk?.url" target="_blank">快速查询报价>></a>
    </p>
    <div style="display: flex">
      <div class="img-box">
        <img src="/images/BWPRO2.png" class="img" />
      </div>
      <div class="img-box">
        <img src="/images/ZZBW2.png" class="img" />
      </div>
    </div>
  </a-modal>
  <OperationalTool v-model:show="show" />
</template>

<script lang="ts" setup name="BasicLayout">
import { computed, h, nextTick, onMounted, onUnmounted, reactive, ref, watchEffect, watch } from 'vue'
import { type RouteRecordRaw, useRouter } from 'vue-router'
import { AppstoreOutlined, MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons-vue'
import { useMainStore } from '@/store/useMainStore'
import { pick } from 'lodash-es'
import { getMenuData } from '@/utils/getMenuData'
import Scrollbar from '@/components/scrollbar/index.vue'
import { Modal, message } from 'ant-design-vue'
import { storeToRefs } from 'pinia'
import is from '@/utils/is'
import { useRegionStore } from '@/store/useRegionStore'
import logout from '@/services/user/logout'
// import { io } from 'socket.io-client'
import getGuide from '@/services/user/getGuide'
import guideClose from '@/services/user/guideClose'
import Guide from '@/components/guide/Guide.vue'
import type { getGuideType, OrderGuide, PriceAsk } from '@/services/user/getGuide'
import OperationalTool from '@/components/operational-tool/OperationalTool.vue'
// import userDetail from '@/services/user/userDetail'
import { IconPark } from '@icon-park/vue-next/es/all'
import userDetailFn from '@/services/user/userDetail'

// 运营工具
const show = ref(false)
function openOperationalTool() {
  show.value = true
}

interface BaseState {
  selectedKeys: string[]
  openKeys: string[]
  collapsed: boolean
}
const collapsed = ref(false)
const router = useRouter()
const mainStore = useMainStore()
const regionStore = useRegionStore()
const { menuData } = getMenuData(router.getRoutes())
const { keepName } = storeToRefs(mainStore)
const [, fetchLogout] = logout()

// 过滤meta里有hidden的route
const formatMenuDate = computed(() => {
  const dfs = (routes: RouteRecordRaw[]) => {
    return routes.filter((route) => {
      route.children = dfs(route.children || [])

      return !route.meta?.hidden
    })
  }

  return dfs(menuData)
})

function listToTree(list: RouteRecordRaw[]): RouteRecordRaw[] {
  const map = {}
  const roots: RouteRecordRaw[] = []

  list.forEach((node) => {
    map[node.name] = node
    const parentName = node.meta?.parent?.path
    if (parentName) {
      const parent = map[parentName]
      if (parent) {
        if (!parent.children) {
          parent.children = []
        }
        parent.children.push(node)
      }
    } else {
      roots.push(node)
    }
  })

  return roots
}

const list = computed(() => {
  return listToTree(formatMenuDate.value)
})

watch(
  () => list.value,
  (val) => {
    console.log(val)
  },
  {
    deep: true,
    immediate: true
  }
)

const baseState = reactive<BaseState>({
  selectedKeys: [],
  openKeys: [list.value[0].path],
  collapsed: false
})

const breadcrumb = computed(() => {
  const initCrumb = router.currentRoute.value.matched
    .filter((item) => item.path !== '/')
    .map((item) => ({
      path: item.path,
      breadcrumbName: item.meta.title || '',
      parent: item.meta.parent || null
    }))

  const result: Array<{
    path: string
    breadcrumbName: unknown
  }> = []

  initCrumb.forEach((item) => {
    if (item.parent !== null) {
      const parent = item.parent as {
        path: string
        title: unknown
      }

      if (is.array(item.parent)) {
        result.push(
          ...item.parent.map((d) => {
            return {
              path: d.path,
              breadcrumbName: d.title
            }
          })
        )
      } else {
        result.push({
          path: parent.path,
          breadcrumbName: parent.title
        })
      }
    }

    const value = pick(item, ['path', 'breadcrumbName'])
    result.push(value)
  })

  return result
})

function handleLogout() {
  Modal.confirm({
    title: '提示',
    content: '是否确定退出当前系统？',
    onOk() {
      fetchLogout()
      nextTick(() => {
        mainStore.removeToken()
        mainStore.removeUserInfo()
        regionStore.removeRegion()
        mainStore.setRegisterRouteFresh(true)
        router.removeRoute('index')
        router.push('/login')
      })
    }
  })
}

function handleLogoClick() {
  router.push('/price-package-df')
}

function handleMenuClick({ key: path }: any) {
  if (path === '/price-package-bc') {
    redirectBC()
  } else if (path === '/price-package') {
    router.push('/price-package-df')
  } else {
    router.push(path)
  }
}

function handleCollapse() {
  collapsed.value = !collapsed.value
  mainStore.setBreakpoint(collapsed.value)
}

function handleBreakpoint(val: boolean) {
  mainStore.setBreakpoint(val)
}

watchEffect(() => {
  if (router.currentRoute) {
    const matched = router.currentRoute.value.matched.concat()
    baseState.selectedKeys = matched
      .filter((r) => r.name !== 'index')
      .map((r) => {
        if (r.meta.activeMenu) {
          return r.meta.activeMenu as string
        }
        return r.path
      })
    // baseState.openKeys = matched.filter((r) => r.path !== router.currentRoute.value.path).map((r) => r.path)
  }
})

//关闭加购引导弹窗
const GuideVisible = ref(false)
const [, guideCloseFn] = guideClose()
async function handleCancel(type: number, id: any) {
  GuideVisible.value = false
  handleClose(type, id)
}
async function handleClose(type: number, id: any) {
  const [err, res] = await guideCloseFn({
    code: type,
    id: id
  })
  if (!err) {
    console.log(res)
  } else {
    message.warn(err.message)
  }
}

//
// 标王pro跳转
// const [, userDetailFn] = userDetail()
// const getBwPro = async () => {
//   const [err, res] = await userDetailFn({
//     id: mainStore.userInfo?.id
//   })
//   if (!err) {
//     if (!res.data.data) {
//       window.open('http://bwpro.e-baixing.com/#/price-package')
//     } else {
//       const user = res.data.data
//       window.open('http://bwpro.e-baixing.com/#/price-package?userId=' + user.id + '&token=' + user.password)
//     }
//   } else {
//     message.warning(err.message)
//   }
// }

// 获取加购引导数据信息
const orderGuide = ref<OrderGuide[]>()
const priceAsk = ref<PriceAsk>()
const [, getGuideFn] = getGuide()
async function getGuideInfo() {
  const [err, res] = await getGuideFn()
  if (!err) {
    orderGuide.value = res.data.data.orderGuide
    priceAsk.value = res.data.data.priceAsk
    if (priceAsk.value) {
      GuideVisible.value = true
    }
    if (orderGuide.value?.length) {
      orderGuide.value.forEach((item) => {
        confirm(item)
      })
    }
  } else {
    message.warn(err.message)
  }
}

function confirm(item: OrderGuide) {
  Modal.confirm({
    mask: false,
    title: null,
    icon: null,
    content: () => h('div', {}, [h(Guide, { item: item })]),
    okText: '关闭',
    style: { width: '900px' },
    cancelButtonProps: { style: { display: 'none' } }
  })
  handleClose(2, [item.orderId])
}

// 定时器发请求
let timeid: number = 0

function start() {
  clearInterval(timeid)
  timeid = window.setInterval(() => {
    getGuideInfo()
  }, 120000)
}

function stop() {
  clearInterval(timeid)
}

const [, userDetailFnFetch] = userDetailFn()

const redirectBC = async () => {
  const [err, res] = await userDetailFnFetch({
    id: mainStore.userId
  })
  if (!err) {
    if (!res.data.data) {
      window.open('http://bwbc.e-baixing.com')
    } else {
      const user = res.data.data
      window.open('http://bwbc.e-baixing.com/?userId=' + user.id + '&token=' + user.password)
    }
  } else {
    message.warning(err.message)
  }
}

onMounted(() => {
  getGuideInfo()
  start()
})

onUnmounted(() => {
  stop()
})

// var socket = io('ws://192.168.2.119:8085/ws', {
//   transports: ['websocket'], // 指定传输方式，如WebSocket
//   autoConnect: true, // 是否自动连接
//   reconnection: true, // 是否自动重新连接
//   reconnectionAttempts: 3, // 重新连接尝试次数
//   reconnectionDelay: 1000, // 重新连接延迟时间（毫秒）
//   query: { token: mainStore.token } // 自定义查询参数
//   // 其他可选参数...
// })
// onMounted(() => {
//   socket.on('connected', (socket) => {
//     socket.emit('hello', 'world')
//   })
// })

// // 组件被销毁之前，清空 sock 对象
// onBeforeUnmount(() => {
//   // 关闭连接
//   // socket.close()
//   // 销毁 websocket 实例对象
//   // socket = null
// })
</script>

<style lang="less" scoped>
.gy {
  color: rgb(184, 183, 183);
}

.img-box {
  width: 48%;
  padding: 10px;
  border: 1px solid #e3e2e2;
  margin-right: 2%;

  .img {
    width: 100%;
  }
}

.header {
  padding: 0;
  height: 48px;
  line-height: 48px;
  width: 100%;
  z-index: 100;
  right: 0;
  position: fixed;
  top: 0;
  box-shadow: 0 1px 4px rgb(0 21 41 / 8%);
}

.main-layout {
  width: 100%;
  min-height: 100vh;
}

.real-sider {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 99;
  height: 100%;
  overflow: hidden;
  padding-top: 48px;
  box-shadow: 2px 0 8px #1d23290d;

  &__fold {
    text-align: left;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 40px;
    line-height: 40px;
    padding: 4px 16px;
    border-top: 1px solid rgba(0, 0, 0, 0.06);

    .fold {
      font-size: 16px;
      line-height: 1;
    }

    .unfold {
      font-size: 16px;
      line-height: 1;
    }
  }
}

.fake-sider {
  width: 208px;
  overflow: hidden;
  flex: 0 0 208px;
  max-width: 208px;
  min-width: 208px;
  transition:
    background-color 0.3s ease 0s,
    min-width 0.3s ease 0s,
    max-width 0.3s cubic-bezier(0.645, 0.045, 0.355, 1) 0s;

  &--collapsed {
    width: 48px;
    max-width: 48px;
    min-width: 48px;
  }
}

.fake-header {
  height: 48px;
  line-height: 48px;
  background: transparent;
}

.layout__right {
  margin-right: 12px;
  cursor: pointer;
  display: flex;

  .btn {
    margin-top: 10px;
  }

  &__username {
    font-size: 14px;
    vertical-align: middle;
    color: #000;
    margin-left: 8px;
  }
}

.header {
  padding: 0 16px 0 23px;

  .title {
    font-size: 22px;
  }
}

.menu {
  padding-bottom: 40px;
  position: relative;

  &-item {
    &__title {
      font-size: 16px;
    }

    &__icon {
      height: 18px;
      line-height: 1;
      margin: 0 15px 0 0;
    }
  }

  &__scroll-bar {
    width: 100%;
    height: calc(100vh - 88px);
  }

  ::v-deep(.ant-menu-item) {
    width: 100%;
  }
}

.breadcrumb {
  display: flex;
  align-items: center;
  margin: 16px 24px;

  &__item {
    display: flex;
    align-items: center;
    font-weight: bold;

    &:last-child {
      font-weight: bold;
      color: rgb(78, 89, 105);
    }
  }

  ::v-deep(.ant-breadcrumb-separator) {
    color: #90869c;
    margin: 0 12px;
  }
}

.layout-content {
  margin: 0 24px 24px;
  border-radius: 5px;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease-in-out;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
